#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import logging
from jinja2 import Environment, FileSystemLoader
import os

log_path = './log/myapp.log'


def makedir_if_not_exists(path):
    """
    Keyword Arguments:
    path --
    """
    floder = os.path.dirname(log_path)
    if not os.path.exists(floder):
        os.makedirs(floder)


def __log():
    # create logger with 'spam_application'
    logger = logging.getLogger('server')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    makedir_if_not_exists(log_path)
    fh = logging.FileHandler(log_path)
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    # add the handlers to the logger
    logger.addHandler(fh)
    logger.addHandler(ch)

    return logger


_log = __log()


def log(*args, **kwargs):
    logger = {
        'debug': _log.debug,
        'info': _log.info,
        'error': _log.error,
    }
    if 'level' in kwargs:
        lg = logger[kwargs['level']]
    else:
        lg = logger['info']
    message = ''.join([str(i) for i in args])
    lg(message)


encode_code = 'utf-8'


# __file__ 就是本文件的名字
# 得到用于加载模板的目录
path = 'templates'
# 创建一个加载器, jinja2 会从这个目录中加载模板
loader = FileSystemLoader(path)
# 用加载器创建一个环境, 有了它才能读取模板文件
env = Environment(loader=loader)

# 调用 template() 方法加载模板并返回
def template(html, **kwargs):
    b = env.get_template(html)
    return b.render(**kwargs)

salt = 'haha'
